package cn.zxyh.filter;

import cn.zxyh.pojo.User;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证用户是否登录，进行拦截
 *
 * @author:man
 * @date:2020/5/25
 */
@Component
public class LoginVerifyFilter implements Filter {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if (isExclusion((HttpServletRequest) request)) {
            // 如果需要排除，直接放行
            filterChain.doFilter(request, response);
            return;
        }
        String token = (String) request.getParameter("access_token");
        Object obj = null;
        if (token != null)
            obj = redisTemplate.opsForValue().get(token);

        if (obj == null) {
            // TODO 返回登录
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("code", 403);
            jsonObj.put("msg", "need login!");
            response.getWriter().println(jsonObj.toJSONString());
            return;
        }
        User user = (User) obj;
        request.setAttribute("user", user);
        filterChain.doFilter(request, response);
    }

    private boolean isExclusion(HttpServletRequest request) {
        return "/login".equals(request.getServletPath()) || "/regist".equals(request.getServletPath());
    }
}
